package demo.javax.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONObject;

import demo.javax.servlet.http.ServletUtils;
import demo.vo.common.ApiResult;
import demo.vo.common.BusinessCode;

/**
 * 
 * 判断用户是否登录
 *
 */
public class AuthFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    private WebApplicationContext wac;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Content-type", "text/html;charset=UTF-8");

        // 过滤非login的请求，必须先验证用户
        HttpServletRequest request = (HttpServletRequest) req;
        String path = request.getServletPath();
        logger.info(path);
        if (path.startsWith("/api")) {
            chain.doFilter(req, res);
            return;
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            logger.info("CorsFilter session == null ");
            ApiResult<Object> result = new ApiResult<>(BusinessCode.NOT_LOGIN.getCode(),
                    BusinessCode.NOT_LOGIN.getMessage());
            ServletUtils.printJsonWriter(JSONObject.toJSONString(result), response);
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(filterConfig.getServletContext());
        this.wac = (WebApplicationContext) filterConfig.getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }

    @Override
    public void destroy() {
        logger.info("invoke method destroy");
    }

}